package com.example.sword;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;

public class Test22 {

    public static void main(String[] args) {

    }


    public class TreeNode {
        int val;
        TreeNode left = null;
        TreeNode right = null;

        TreeNode(int val) {
            this.val = val;
        }
    }

    /**
     * 从上往下打印出二叉树的每个节点，同层节点从左至右打印。
     */

    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        if (root==null)return null;
        ArrayList<Integer> ans = new ArrayList<>();
        Deque<TreeNode> deque = new LinkedList();
        //offer 和 add一样 添加到队列或者链表的尾部
        deque.offer(root);
        while (!deque.isEmpty()){
            TreeNode temp = deque.pop();
            ans.add(temp.val);
            if (temp.left!=null){
                deque.add(temp.left);
            }
            if (temp.right!=null){
                deque.add(temp.right);
            }
        }

        return ans;
    }

}
